using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Input;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 重命名对话框
    /// </summary>
    public partial class RenameDialog : Window
    {
        /// <summary>
        /// 新名称
        /// </summary>
        public string NewName { get; private set; } = string.Empty;

        /// <summary>
        /// 是否为目录
        /// </summary>
        private readonly bool _isDirectory;

        /// <summary>
        /// 原始名称
        /// </summary>
        private readonly string _originalName;

        public RenameDialog(string currentName, bool isDirectory)
        {
            InitializeComponent();
            
            _originalName = currentName;
            _isDirectory = isDirectory;
            
            InitializeDialog();
        }

        /// <summary>
        /// 初始化对话框
        /// </summary>
        private void InitializeDialog()
        {
            // 设置标题
            TitleText.Text = _isDirectory ? "重命名文件夹" : "重命名文件";
            
            // 设置输入框内容
            NameTextBox.Text = _originalName;
            
            // 如果是文件，选中文件名部分（不包括扩展名）
            if (!_isDirectory && Path.HasExtension(_originalName))
            {
                var nameWithoutExtension = Path.GetFileNameWithoutExtension(_originalName);
                NameTextBox.Focus();
                NameTextBox.SelectionStart = 0;
                NameTextBox.SelectionLength = nameWithoutExtension.Length;
            }
            else
            {
                // 如果是文件夹或无扩展名文件，选中全部
                NameTextBox.Focus();
                NameTextBox.SelectAll();
            }

            // 绑定文本变化事件
            NameTextBox.TextChanged += NameTextBox_TextChanged;
            
            // 设置提示信息
            UpdateHintText();
        }

        /// <summary>
        /// 更新提示信息
        /// </summary>
        private void UpdateHintText()
        {
            if (_isDirectory)
            {
                HintText.Text = "提示：文件夹名不能包含以下字符：\\ / : * ? \" < > |";
            }
            else
            {
                HintText.Text = "提示：文件名不能包含以下字符：\\ / : * ? \" < > |";
            }
        }

        /// <summary>
        /// 文本框内容变化事件
        /// </summary>
        private void NameTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            ValidateInput();
        }

        /// <summary>
        /// 验证输入
        /// </summary>
        private void ValidateInput()
        {
            var newName = NameTextBox.Text.Trim();
            var isValid = IsValidName(newName);
            
            OkButton.IsEnabled = isValid && !string.IsNullOrWhiteSpace(newName) && newName != _originalName;
            
            // 更新提示文本颜色
            if (string.IsNullOrWhiteSpace(newName))
            {
                HintText.Foreground = FindResource("MaterialDesignBodyLight") as System.Windows.Media.Brush;
                UpdateHintText();
            }
            else if (!isValid)
            {
                HintText.Foreground = System.Windows.Media.Brushes.Red;
                HintText.Text = "❌ 名称包含无效字符或为系统保留名称";
            }
            else if (newName == _originalName)
            {
                HintText.Foreground = FindResource("MaterialDesignBodyLight") as System.Windows.Media.Brush;
                HintText.Text = "💡 名称未更改";
            }
            else
            {
                HintText.Foreground = System.Windows.Media.Brushes.Green;
                HintText.Text = "✅ 名称有效";
            }
        }

        /// <summary>
        /// 验证名称是否有效
        /// </summary>
        private bool IsValidName(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
                return false;

            // 检查是否包含无效字符
            var invalidChars = Path.GetInvalidFileNameChars();
            if (name.Any(c => invalidChars.Contains(c)))
                return false;

            // 检查是否为保留名称
            var reservedNames = new[] { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" };
            var nameWithoutExtension = Path.GetFileNameWithoutExtension(name).ToUpper();
            if (reservedNames.Contains(nameWithoutExtension))
                return false;

            // 检查长度
            if (name.Length > 255)
                return false;

            // 检查是否以点或空格结尾
            if (name.EndsWith(".") || name.EndsWith(" "))
                return false;

            return true;
        }

        /// <summary>
        /// 文本框按键事件
        /// </summary>
        private void NameTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && OkButton.IsEnabled)
            {
                Ok_Click(sender, e);
            }
            else if (e.Key == Key.Escape)
            {
                Cancel_Click(sender, e);
            }
        }

        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private void Ok_Click(object sender, RoutedEventArgs e)
        {
            var newName = NameTextBox.Text.Trim();
            
            if (string.IsNullOrWhiteSpace(newName))
            {
                MessageBox.Show("请输入有效的名称", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                NameTextBox.Focus();
                return;
            }

            if (!IsValidName(newName))
            {
                MessageBox.Show("名称包含无效字符或为系统保留名称，请重新输入", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                NameTextBox.Focus();
                NameTextBox.SelectAll();
                return;
            }

            if (newName == _originalName)
            {
                MessageBox.Show("新名称与原名称相同", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                NameTextBox.Focus();
                NameTextBox.SelectAll();
                return;
            }

            NewName = newName;
            DialogResult = true;
            Close();
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }
    }
}
